package controller

import (
	"github.com/gin-gonic/gin"
	"github.com/gomodule/redigo/redis"
	"math/rand"
	"net/http"
	"strconv"
	"strings"
	"testGin/entity"
	"testGin/tool"
)

func GetTenVideo(c *gin.Context) {
	info, err := tool.ParseToken(c.GetHeader("Authorization"))
	var user entity.User
	if err == nil {
		user.Id = info.UserId
		user.Username = info.Issuer
		user.IsAuth = true
	}
	var srr [10]entity.Video
	var arr [10]int
	for i := 0; i < 10; i++ {
		video := GetOneVideo(user)
		flag := false
		for j := 0; j < len(arr); j++ {
			if video.Id == arr[j] {
				flag = true
				break
			}
		}
		if flag == false {
			srr[i] = video
			arr[i] = video.Id
		} else {
			i--
		}
	}
	c.JSON(http.StatusOK, tool.R{
		200, "ok", srr,
	})
}

func GetOneVideo(user entity.User) entity.Video {
	var id int
	var srr []string
	// 如果用户登录了，则使用推荐算法
	if user.IsAuth == true {
		u := new(entity.User)
		GetDB().Where("id = ?", user.Id).First(&u)
		// 用户添加的喜欢看的类型都放入数组
		srr = strings.Split(u.Type, ",")
	}
	// 生成1-12的随机数
	id = rand.Intn(12) + 1
	// 如果数组等于0，说明: 1、用户未登录  2、用户未选择喜好 进行随机算法即可
	if len(srr) != 0 {
		r := rand.Intn(len(srr)) // [0-len(srr))
		id, _ = strconv.Atoi(srr[r])
		// 生成1-100，如果数字小于30就，随机推荐
		// 用户观看的时候70% 是自己喜欢的，30%是随机的
		// 如果不登录100%是随机的
		re := rand.Intn(100) + 1
		if re <= 30 {
			id = rand.Intn(12) + 1
		}
	}
	var video entity.Video
	GetDB().Where("type = ?", id).Order("RAND()").First(&video)
	video = VideoFill(video)
	video = getCollectAndLoveNum(video)
	if user.IsAuth == true {
		video = isCollectAndLove(user.Id, video)
	}
	return video
}

func GetVideoByType(c *gin.Context) {
	// 判断是否登录
	info, err := tool.ParseToken(c.GetHeader("Authorization"))
	var videos []entity.Video
	tid, _ := strconv.Atoi(c.Param("tid"))

	if tid > 13 || tid < 1 {
		c.JSON(http.StatusForbidden, tool.R{
			403, "请求参数错误", nil,
		})
		return
	}
	GetDB().Where("type = ?", tid).Find(&videos)
	for i := 0; i < len(videos); i++ {
		videos[i] = getCollectAndLoveNum(videos[i])
		if err == nil { // 如果登录的话
			videos[i] = isCollectAndLove(info.UserId, videos[i])
		}
	}
	videos = VideosFill(videos)
	c.JSON(http.StatusOK, tool.R{
		200, "ok", videos,
	})
}

func GetVideoByUpload(c *gin.Context) {
	upload := entity.GetUserVideoCollectLoveUpload(c)
	var videos []entity.Video
	GetDB().Table("video").Where("uid = ?", upload.Uid).Find(&videos)
	for i := 0; i < len(videos); i++ {
		videos[i] = getCollectAndLoveNum(videos[i])
		videos[i] = isCollectAndLove(upload.Uid, videos[i])
	}
	videos = VideosFill(videos)
	c.JSON(http.StatusOK, tool.R{
		200, "ok", videos,
	})
}

// 获取点赞收藏和分享的总数量
func getCollectAndLoveNum(video entity.Video) entity.Video {
	// 注意使用管道的时候必须使用一个conn对象，否则卡主
	conn := GetRedisConn()
	// 使用管道
	conn.Send("Get", "C:"+strconv.Itoa(video.Id))
	conn.Send("Get", "L:"+strconv.Itoa(video.Id))
	conn.Send("Get", "S:"+strconv.Itoa(video.Id))
	conn.Flush()
	// 从管道接收数据
	video.CollectNum, _ = redis.String(conn.Receive())
	video.LoveNum, _ = redis.String(conn.Receive())
	video.ShareNum, _ = redis.String(conn.Receive())

	video.CollectNum = parseZero(video.CollectNum)
	video.LoveNum = parseZero(video.LoveNum)
	video.ShareNum = parseZero(video.ShareNum)
	return video
}

// 判断当前登录用户是否点赞和收藏
func isCollectAndLove(id int, video entity.Video) entity.Video {
	var num1, num2 int64
	conn := GetDB()
	conn.Table("collect").Where("uid = ? and vid = ?", id, video.Id).Count(&num1)
	conn.Table("love").Where("uid = ? and vid = ?", id, video.Id).Count(&num2)
	video.IsCollet = !(num1 == 0)
	video.IsLove = !(num2 == 0)
	return video
}

func parseZero(num string) string {
	if num == "" {
		num = "0"
	}
	return num
}
